import { useEffect, useContext, useState, useMemo } from 'react';
import { Button, Card, Row, Col } from 'antd';
import { connect, history } from 'umi';

import '../common/style.less';
import { ProcurementMethodContext } from '../common/ProcurementMethodContext';

import pageStyles from '@/common/pageLayout.less';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { Descriptions, useDescriptions } from '@/components/Descriptions';
import { getKeyRouter, getPosIDs, getUserID } from '@/utils';
import { FormOutlined } from '@ant-design/icons';
import { WorkflowChedkRecord } from '@/components/WorkflowCommonCopy';
import { BGflowBusinessType, BGrequestController, FSBG_STATE_QC, FSBG_STATE_SHZ, FSBG_STATE_ZF } from '../common/Format';

const ProcurementMethodUpdateView: React.FC<any> = ({ locationProps, curRes }) => {
  const { prefixCls } = useContext(ProcurementMethodContext);

  // 页面状态
  const [typeState, setTypeState] = useState<string>('view');

  // 审批记录渲染控制
  const [isShowAuditRecord, setIsShowAuditRecord] = useState<boolean>(false);

  const { info = {}, type } = locationProps?.state || {};
  // 表格表单配置信息
  const [config, { setFieldsValue, validateFields }] = useDescriptions({
    labelWidth: 180,
    disabled: true,
    schemas: [
      {
        label: '采购项目名称',
        field: 'applyName',
        component: 'Input',
        required: true,
        disabled: true,
      },
      {
        label: '采购单位',
        field: 'applyDepartmentName',
        component: 'Input',
        required: true,
        disabled: true,
      },
      {
        label: '原采购方式',
        field: 'recommendedName',
        component: 'Input',
        required: true,
        disabled: true,
      },
      {
        label: '拟采用采购方式',
        field: 'businessTypeName',
        component: 'Select',
        required: true,
        options: [
          {
            name: '公开招标',
            value: '公开招标',
          },
          {
            name: '邀请招标',
            value: '邀请招标',
          },
          {
            name: '竞争性谈判',
            value: '竞争性谈判',
          },
        ],
      },
      {
        label: '预算金额（元）',
        field: 'expectSum',
        component: 'Input',
        required: true,
        disabled: true,
        colSpan: 2,
      },
      {
        label: '采购方式变更理由',
        field: 'info',
        component: 'InputTextArea',
        required: true,
        showCount: true,
        allowClear: true,
        maxLength: 200,
        autoSize: { minRows: 4, maxRows: 6 },
        colSpan: 2,
      },
    ],
  });

  /**
   * 处理工作流功能 权限
   */
  const workflowPowerAllBtn = useMemo(() => {
    let pownerBtn: Record<string, any> = {
      revokeFlagBtn: false, //撤销按钮
      invalBoolBtn: false, //暂停开始按钮
      stopProcInstBtn: false, //流程作废接口
    };
    if (info?.state == FSBG_STATE_SHZ()) {
      pownerBtn['revokeFlagBtn'] = true;
      pownerBtn['stopProcInstBtn'] = true;
    }

    const taskType: string = BGflowBusinessType();
    const taskHandInfo: Record<string, any> = info?.paramObject?.[taskType];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      pownerBtn['invalBoolBtn'] = true;
    }
    return pownerBtn;
  }, [info]);

  /**
   * @submit 提交事件
   */
  const submit = async () => {
    const result = await validateFields();
    history.push({
      pathname: `/purchaseApplyController/addApply/:${getKeyRouter()}${getKeyRouter()}`,
      state: {
        type: 'edit',
        info: {
          ...info,
          ...result,
        },
        step: 1,
        source: 'apply',
      },
    });
  };

  /**回显数据 */
  useEffect(() => {
    if (Object.keys(info).length) {
      const param = {
        applyName: '科研团队_2023_0302_采购合金材料',
        applyDepartmentName: '怀柔实验室',
        recommendedName: '公开招标',
        businessTypeName: '竞争性谈判',
        expectSum: '1200.00',
        info: '采购合金材料需要申请变更',
      };
      setFieldsValue(param);
      setTypeState(type);
    }
  }, [info, type]);

  return (
    <div className={prefixCls}>
      <Card
        title={'变更采购方式'}
        className={pageStyles['page-view-cardView']}
        bodyStyle={{
          padding: '5px 0px',
        }}
      >
        <div className={prefixCls}>
          <div className={`${prefixCls}-container`}>
            <ScrollBarLayout>
              <Descriptions config={config} />
            </ScrollBarLayout>
          </div>
          {typeState == 'check' && (
            <div className={`${prefixCls}-footer`}>
              <Button
                // icon={<FormOutlined />}
                onClick={() => {
                  setIsShowAuditRecord(!isShowAuditRecord);
                }}
              >
                办理
              </Button>
            </div>
          )}
        </div>
      </Card>
      {typeState == 'check' && (
        <Row
          gutter={[0, 0]}
          style={{
            margin: '3px 0 0',
          }}
        >
          <Col span={24}>
            {/* 审核记录 */}
            <WorkflowChedkRecord
              curRes={curRes}
              dataDetailInfo={info}
              flowBusinessType={BGflowBusinessType()}
              requestController={BGrequestController()}
              reloadPageCallback={() => {}} // 刷新方法-详情方法
              revokeStateID={FSBG_STATE_QC()}
              allBtnFuncQuqry={workflowPowerAllBtn}
              tabPaneHeight={0.35}
              isCheckDrawer={true}
              isShowCollapse={isShowAuditRecord}
              changeCollapse={(val) => {
                setIsShowAuditRecord(val);
              }}
              cancelStateId={FSBG_STATE_ZF()}
            />
          </Col>
        </Row>
      )}
    </div>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(ProcurementMethodUpdateView);
